package model

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ ConfigModel = (*customConfigModel)(nil)

type (
	// ConfigModel is an interface to be customized, add more methods here,
	// and implement the added methods in customConfigModel.
	ConfigModel interface {
		configModel
		FindOneByKey(ctx context.Context, key, area string) (*Config, error)
		UpdateStatusById(ctx context.Context, id, status int64) error
	}

	customConfigModel struct {
		*defaultConfigModel
	}
)

func (c *customConfigModel) UpdateStatusById(ctx context.Context, id, status int64) error {
	configIdKey := fmt.Sprintf("%s%v", cacheConfigIdPrefix, id)
	_, err := c.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
		query := fmt.Sprintf("update %s set %s where `id` = ?", c.table, "status=?")
		return conn.ExecCtx(ctx, query, status, id)
	}, configIdKey)
	return err
}

func (c *customConfigModel) FindOneByKey(ctx context.Context, key, area string) (*Config, error) {
	var resp Config
	query := fmt.Sprintf("select %s from %s where `key` = ? and area = ? limit 1", configRows, c.table)
	err := c.QueryRowNoCacheCtx(ctx, &resp, query, key, area)

	switch {
	case err == nil:
		return &resp, nil
	case errors.Is(err, sqlx.ErrNotFound):
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

// NewConfigModel returns a model for the database table.
func NewConfigModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) ConfigModel {
	return &customConfigModel{
		defaultConfigModel: newConfigModel(conn, c, opts...),
	}
}
